package cn.lxs.web.download;

import cn.lxs.web.utils.DownLoadUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
@WebServlet("/downLoadServlet")
public class DownLoad extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求参数,得到文件名称
        String file = req.getParameter("filename");
        //使用字节输入流加载文件
        ServletContext context = this.getServletContext();
        String realPath = context.getRealPath("/img/"+file);

        //设置response的响应头
        String mimeType = context.getMimeType(file);
        //获取文件的类型
        resp.setHeader("content-type",mimeType);
        //这里是设置头的类型
        resp.setHeader("content-disposition","attachment;filename="+file);
        //这里是指以附件形式打开,后面的参数是提示出来的下载的文件名称

        //解决文件下载的中文问题
        //获取user-agent的开头
        String agent = req.getHeader("user-agent");
        //使用工具类
        file = DownLoadUtils.getFileName(agent, file);


        //使用字节流关联
        FileInputStream fis = new FileInputStream(realPath);
        ServletOutputStream sos = resp.getOutputStream();
        byte[] buff = new byte[1024*8];
        int len=0;
        while((len=fis.read(buff))!=-1)
        {
            sos.write(buff,0,len);
        }
        fis.close();
    }
}
